<template>
  <client-only>
    <div class="editor-box" style="border: 1px solid #ccc">
      <Toolbar
        class="toolbar"
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        class="editor"
        style="height: 200px; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
        @onBlur="handleBlur"
      />
    </div>
  </client-only>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import {
  onBeforeUnmount,
  ref,
  shallowRef,
  watch,
  defineProps,
  defineEmits,
  defineExpose,
  onMounted,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import { useUserStore } from "@/stores/User.js";
const userStore = useUserStore();

const props = defineProps({
  content: {
    type: String,
    default: "",
  },
});
const emits = defineEmits("setEditorValue", "blur");

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref(props.content || "");
// const valueHtml = computed(() => {
//   return props.content || ''
// })

const toolbarConfig = {
  // 去除视频插入
  excludeKeys: ["group-video"],
};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {},
};

// 上传图片配置
// editorConfig.MENU_CONF['uploadImage'] = {
//   // form-data fieldName ，默认值 'wangeditor-uploaded-image'
//   fieldName: 'your-custom-name',

//   // 单个文件的最大体积限制，默认为 2M
//   maxFileSize: 10 * 1024 * 1024, // 1M

//   // 最多可上传几个文件，默认为 100
//   maxNumberOfFiles: 10,

//   // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
//   allowedFileTypes: ['image/*'],

//   // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
//   meta: {
//     token: person.token,
//   },

//   // 将 meta 拼接到 url 参数中，默认 false
//   metaWithUrl: false,

//   // 自定义增加 http  header
//   headers: {
//     Accept: 'text/x-json',
//   },

//   // 跨域是否传递 cookie ，默认为 false
//   withCredentials: false,

//   // 超时时间，默认为 10 秒
//   timeout: 5 * 1000, // 5 秒

//   onSuccess(file, res) {
//     console.log(file, res, '上传成功')
//   },
// }

// 自定义上传图片
editorConfig.MENU_CONF["uploadImage"] = {
  async customUpload(file, insertFn) {
    const res = await axios({
      baseURL: "https://admin.testace.cn/fenglingClient" + "/client/uploads",
      timeout: 99999,
      headers: {
        "Content-Type": "multipart/form-data",
        token: userStore.userInfo.token,
      },
      method: "POST",
      data: {
        savePath: "fengling",
        file: file,
      },
    });

    console.log(res, "上传成功");
    if (res.data.code === "000000") {
      const alt = ""; //图片介绍
      const href = ""; //图片链接
      insertFn(res.data.data.url, alt, href); //文件URL回显在富文本内方法
      ElMessage({
        type: "success",
        message: "上传成功",
      });
    } else {
      ElMessage({
        type: "error",
        message: res.data.info,
      });
    }
  },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

// 失焦事件
const handleBlur = () => {
  emits("blur", valueHtml.value);
};

watch(
  () => props.content,
  (val) => {
    if (val) {
      valueHtml.value = val;
    }
  }
);

watch(
  () => valueHtml.value,
  (val) => {
    if (val === "<p><br></p>") {
      emits("setEditorValue", "");
    } else {
      emits("setEditorValue", val);
    }
  }
);

defineExpose({ valueHtml: valueHtml.value });
</script>

<style lang="scss" scoped>
.editor {
  :deep() {
    .w-e-text-container p {
      margin: 5px 0 !important;
    }

    .w-e-text-placeholder {
      top: 0 !important;
    }

    .w-e-modal {
      position: fixed;
      top: 70px !important;
      left: 230px !important;
    }
  }
}

.editor-box {
  &.w-e-full-screen-container {
    z-index: 99 !important;
  }
}
</style>
